package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CategoryBrandService categoryBrandService;


    @Override
    public List<CategoryDTO> queryCategoryByPid(Long pid) {
        List<Category> categories = this.query().eq("parent_id", pid).list();
        return CategoryDTO.convertEntityList(categories);
    }

    @Override
    public CategoryDTO queryCategoryById(Long id) {
        return new CategoryDTO(getById(id));
    }

    @Override
    public List<CategoryDTO> queryCategoryByIds(Long[] ids) {
        ArrayList<Category> categories = new ArrayList<>();
        for (Long id : ids) {
            Category category = getById(id);
            categories.add(category);
        }
        return CategoryDTO.convertEntityList(categories);
    }

    @Override
    public List<CategoryDTO> queryCategoryByBrandId(Long brand_id) {
        //根据品牌id  查询中间表 叨叨对应的分类id
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("brand_id", brand_id).list();
        //如果查询到的结果为空 则返回空
        if (categoryBrandList.isEmpty()) {
            return Collections.emptyList();
        }
        //jdk8的新特性 stream流  获取分类的id集合
        List<Long> categoryIdList = categoryBrandList.stream().map(CategoryBrand::getCategoryId).collect(Collectors.toList());
        //根据分类id集合 查询分类对象集合
        List<Category> categories = listByIds(categoryIdList);
        //转换DTO
        return CategoryDTO.convertEntityList(categories);
    }
}
